<template>
  <div class="table-container">
    <el-table ref="tableRef" :data="tableData" :height="tableHeight" :row-class-name="lockedRowClass" border
              size="small" @row-click="handleClick" @filter-change="handleFilterChange">
      <el-table-column :filter-multiple="false" :filters="gunFilterList" align="center" label="枪号" prop="gunNo"
                       width="65px"></el-table-column>
      <el-table-column align="center" label="油品" prop="fuelName">
        <template slot-scope="scope">
          <span>{{ scope.row.fuelName }} {{ scope.row.fuelLitre }}L</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="应收" prop="fuelAmount"></el-table-column>
      <el-table-column align="center" label="实收" prop="payAmount"></el-table-column>
      <el-table-column :filter-multiple="false" :filters="payTypeList" align="center" label="结算方式"
                       prop="paymentTypeName" width="100px"></el-table-column>
      <el-table-column :formatter="timeSimplify" align="center" label="加油时间" prop="fuelEndTime"></el-table-column>
      <el-table-column :formatter="timeSimplify" align="center" label="结算时间" prop="operationTime"></el-table-column>
    </el-table>
    <div class="pager">
      <el-pagination :current-page="currentPage" :page-size="pageSize" :total="dataListAfterFilter.length"
                     layout="total, prev, pager, next" @prev-click="handlePrevClick" @next-click="handleNextClick"
                     @current-change="handleCurrentChange"></el-pagination>
    </div>
    <!-- 详情弹窗 -->
    <el-dialog
        :visible.sync="dialogVisible"
        title="消费信息详情">
      <el-form class="info-form" size="medium" status-icon>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="12"><span class="form-span">油枪：{{ currentRow ? currentRow.gunNo : '' }}</span></el-col>
            <el-col :span="12"><span class="form-span">油品：{{ currentRow ? currentRow.fuelName : '' }}</span></el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="12"><span class="form-span">加油升数：{{ currentRow ? currentRow.fuelLitre : '' }} 升</span>
            </el-col>
            <el-col :span="12"><span class="form-span">油机金额：{{ currentRow ? currentRow.fuelAmount : '' }} 元</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">

            <el-col :span="12"><span class="form-span">挂牌价格：{{
                currentRow ? currentRow.fuelPrice : ''
              }} 元/升</span>
            </el-col>
            <el-col :span="12"><span class="form-span">结算单价：{{
                currentRow ? currentRow.settlementUnitPrice : ''
              }} 元/升</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="12"><span class="form-span"> 券 优 惠 ：{{
                currentRow ? currentRow.couponDiscount : ''
              }} 元</span></el-col>
            <el-col :span="12"><span
                class="form-span">合计优惠：{{
                currentRow ? (currentRow.fuelAmount - currentRow.payAmount).toFixed(2) : ''
              }} 元</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="12"><span class="form-span">结算方式：{{
                currentRow ? currentRow.paymentTypeName : ''
              }}</span>
            </el-col>
            <el-col :span="12"><span class="form-span">实收金额：{{ currentRow ? currentRow.payAmount : '' }} 元</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="12"><span class="form-span">支付状态：{{ currentRow ? currentRow.payStatusName : '' }}</span>
            </el-col>
            <el-col :span="12"><span class="form-span">顾客昵称：{{ currentRow ? currentRow.memberName : '' }}</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="12"><span class="form-span"> 流 水 号 ：{{ currentRow ? currentRow.fuelRecordId : '' }}</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="12"><span class="form-span"> 加油时间：{{
                currentRow ? timeFormatter(currentRow.fuelEndTime) : ''
              }}</span></el-col>
            <el-col :span="12"><span
                class="form-span"> 结算时间：{{ currentRow ? timeFormatter(currentRow.operationTime) : '' }}</span>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-show="showRefund" style="float:left;" type="danger" @click="showAuthDialog = true">退款</el-button>
        <el-button icon="el-icon-s-custom" type="success" @click="showFastPayHistory = true">秒付历史</el-button>
        <el-button icon="el-icon-printer" type="danger" @click="printInvoice">打印发票</el-button>
        <!--        <el-button icon="el-icon-printer" type="warning" @click="printReceipt('invoice')">发票小票</el-button>-->
        <el-button icon="el-icon-printer" type="success" @click="printReceipt('invoice')">打印小票</el-button>
        <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
      </span>
      <check-authorize :checkKey="'pos-client.fuel-refund'" :errMsg="'该账户无退款权限'"
                       :showAuthDialog="showAuthDialog"
                       @authPass="handleRefund" @hideAuthDialog="showAuthDialog = false"></check-authorize>
      <fast-pay-history :fuel-record-id="currentRow.fuelRecordId" :visible="showFastPayHistory"
                        @hideHistory="showFastPayHistory = false"></fast-pay-history>
    </el-dialog>
  </div>
</template>
<script>
import {mapGetters} from 'vuex'
import moment from 'moment'
import {fuelRefund} from '@/api/settle'
import {getFuelReceiptText, getSaleFuelInvoiceQrcode} from '@/utils/receipt'
import CheckAuthorize from './CheckAuthorize.vue'
import FastPayHistory from './FastPayHistory.vue'
import {getCardConsumptionRecord, getCardInfoByUid} from '@/api/card'
import {getInvoiceRecord} from '@/api/invoice'

export default {
  name: 'SaleFuelRecord',
  components: {
    CheckAuthorize,
    FastPayHistory
  },
  data () {
    return {
      dialogVisible: false,
      currentRow: {},
      currentPage: 1,
      showAuthDialog: false,
      showFastPayHistory: false
    }
  },
  computed: {
    tableData () {
      if (this.currentPage * this.pageSize > this.dataListAfterFilter.length) {
        return this.dataListAfterFilter.slice(this.pageSize * (this.currentPage - 1), this.dataListAfterFilter.length)
      } else {
        return this.dataListAfterFilter.slice(this.pageSize * (this.currentPage - 1), this.pageSize * this.currentPage)
      }
    },
    ...mapGetters([
      'contentHeight',
      'saleFuelList',
      'stationId',
      'operator',
      'pageSize',
      'gunList',
      'filterGun',
      'filterPayType',
      'wxServerUrl'
    ]),
    tableHeight () {
      return (this.contentHeight - 285) + 'px'
    },
    showRefund () {
      return this.currentRow && this.currentRow.payStatus === 1
    },
    gunFilterList () {
      return this.gunList.map(item => {
        return {text: item.gunNo + '号枪', value: item.gunNo}
      })
    },
    payTypeList () {
      var tmpList = Array.from(new Set(this.saleFuelList.map(item => item.paymentTypeName + ';' + item.paymentType)))
      return tmpList.map(item => {
        var names = item.split(';')
        return {text: names[0], value: names[1]}
      })
    },
    dataListAfterFilter () {
      return this.payTypeFilter(this.chosenGunFilter(this.saleFuelList))
    }
  },
  mounted () {
  },
  methods: {
    chosenGunFilter (dataList) {
      if (this.filterGun) {
        return dataList.filter(item => item.gunNo === this.filterGun)
      } else {
        return dataList
      }
    },
    payTypeFilter (dataList) {
      if (this.filterPayType) {
        return dataList.filter(item => item.paymentType === this.filterPayType)
      } else {
        return dataList
      }
    },
    timeFormatter (time) {
      return moment(time).format('YYYY-MM-DD HH:mm:ss')
    },
    timeSimplify (row, column) {
      return row[column.property] ? moment(row[column.property]).format('HH:mm:ss') : ''
    },
    lockedRowClass ({row, rowIndex}) {
      return row.locked ? 'locked' : ''
    },
    handleClick (row, column, event) {
      console.log('handleClick')
      console.log(row)
      this.dialogVisible = true
      this.currentRow = row
      console.log('结算单价')
      this.currentRow.settlementUnitPrice = (this.currentRow.fuelPrice - ((this.currentRow.couponDiscount + this.currentRow.systemDiscount) / this.currentRow.fuelLitre)).toFixed(2)
    },
    handleRefund () {
      console.log('handleRefund')
      console.log(this.currentRow)
      this.$confirm('确定要发起退款操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = JSON.parse(JSON.stringify(this.currentRow))
        params.operator = this.operator
        fuelRefund(params).then(res => {
          console.log(res)
          this.$message.success(res.msg || '退款成功！')
          this.dialogVisible = false
        }).catch(err => {
          console.log(err)
          this.$message.error(err || '退款失败！')
        })
      }).catch(() => {
        console.log('取消')
      })
    },
    async printReceipt (type) {
      this.$message.success('操作成功')
      var data = JSON.parse(JSON.stringify(this.currentRow))
      // 如果开启了发票二维码
      if (type === 'invoice') {
        data.qrcode = await getSaleFuelInvoiceQrcode(data)
      }
      if (data.cardUid && data.fuelRecordId) {
        getCardConsumptionRecord(data.fuelRecordId).then(res => {
          console.log(res)
          // 把卡的余额信息写如到记录中
          data.balance = res.data.balance
          getCardInfoByUid(data.cardUid).then(res => {
            data.cardNo = res.data.cardNo
            data.cardName = res.data.cardName
            data.username = res.data.username
            data.carNumber = res.data.carNumber
            data.invoiceType = res.data.invoiceType
            this.$store.dispatch('addToReceiptList', getFuelReceiptText(data))
          })
        }).catch(err => {
          console.log(err)
          this.$store.dispatch('addToReceiptList', getFuelReceiptText(data))
        })
      } else {
        this.$store.dispatch('addToReceiptList', getFuelReceiptText(data))
      }
    },
    handlePrevClick (page) {
      this.currentPage = page
    },
    handleNextClick (page) {
      this.currentPage = page
    },
    handleCurrentChange (page) {
      this.currentPage = page
    },
    handleFilterChange (data) {
      console.log('handleFilterChange')
      // console.log(data)
      var tmpList = data[Object.keys(data)[0]]
      if (tmpList.length > 0) {
        console.log(tmpList[0])
        // 如果是数字，说明为选中的枪号，如果不是数字，说明选中的是支付方式
        if (!isNaN(tmpList[0])) {
          this.$store.dispatch('setFilterGun', tmpList[0])
        } else {
          this.$store.dispatch('setFilterPayType', tmpList[0])
        }
        this.currentPage = 1
      } else {
        console.log('清除选中油枪')
        this.$store.dispatch('setFilterGun', '')
        this.$store.dispatch('setFilterPayType', '')
        this.$refs['tableRef'].clearFilter()
      }
    },
    printInvoice () {
      console.log('printInvoice')
      let data = JSON.parse(JSON.stringify(this.currentRow))
      console.log(data)
      // 根据流水号查找对应的开票记录
      getInvoiceRecord(data.fuelRecordId).then(res => {
        console.log(res)
        // 判断是否开票成功，也就是PDF地址是否存在，存在则下载该pdf文件并执行打印操作
        if (res.data && res.data.invoiceUrl) {
          console.log(res.data.invoiceUrl)
          // 添加到打印队列
          this.$store.dispatch('addToInvoiceList', res.data.invoiceUrl)
        }
      }).catch(err => {
        console.log(err)
        this.$message.warning(err || '查找开票记录失败！')
      })
    }
  }
}
</script>
<style scoped>
.table-container {
  width: 100%;
  height: 100%;
}

.form-span {
  font-family: "Helvetica Neue", Helvetica, Arial, "PingFang SC", "Hiragino Sans GB", "Heiti SC", "Microsoft YaHei", "WenQuanYi Micro Hei", sans-serif;
  font-size: 18px;
  font-weight: bold;
}

.el-form-item {
  margin-bottom: 5px;
}

.info-form {
  padding: 10px 30px;
}

.pager {
  text-align: center;
  padding: 5px;
  background: white;
}
</style>
<style>
.el-table .locked {
  background: #E6A23C;
  color: white;
}

.el-table-filter {
  max-height: 80%;
  overflow-y: auto;
}
</style>
